from app import db
from datetime import datetime

class FocusSession(db.Model):
    __tablename__ = 'focus_sessions'
    
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(10))  # 'focus' 或 'break'
    start_time = db.Column(db.DateTime, nullable=False)
    end_time = db.Column(db.DateTime)
    duration = db.Column(db.Integer)  # 持续时间（秒）
    goal_id = db.Column(db.Integer, db.ForeignKey('goals.id'), nullable=True)
    completed = db.Column(db.Boolean, default=False)
    quality = db.Column(db.Integer, nullable=True)  # 1-5 评分
    note = db.Column(db.Text, nullable=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    goal = db.relationship('Goal', backref=db.backref('sessions', lazy=True))
    
    def to_dict(self):
        """转换为字典，适当处理时间字段"""
        # 辅助函数，确保时间序列化正确
        def format_datetime(dt):
            if not dt:
                return None
            try:
                # 确保返回带时区的ISO格式
                return dt.isoformat(timespec='seconds')
            except Exception as e:
                print(f"时间格式化出错: {e}")
                return str(dt)
        
        return {
            'id': self.id,
            'type': self.type,
            'start_time': format_datetime(self.start_time),
            'end_time': format_datetime(self.end_time),
            'duration': self.duration,
            'goal_id': self.goal_id,
            'goal_name': self.goal.name if self.goal else None,
            'completed': self.completed,
            'quality': self.quality,
            'note': self.note,
            'created_at': format_datetime(self.created_at)
        } 